package metamodel.coreservices;

import metamodel.FlatProperty;

import java.util.LinkedList;
import java.util.Iterator;

/**
 * Keeps a list of mappers and asks them for a PROPERTY_MAPPING.
 * The first non null value is returned
 */
public class DelegatingStringMapper implements StringMapper{
    LinkedList list=new LinkedList();

    public void addFirst(final StringMapper o) {
        list.addFirst(o);
    }

    public boolean add(final StringMapper o) {
        return list.add(o);
    }

    public String toString(FlatProperty descriptor, Object value) {
        for (Iterator iterator = list.iterator(); iterator.hasNext();) {
            StringMapper stringMapper = (StringMapper) iterator.next();
            String mapping = stringMapper.toString(descriptor, value);
            if (mapping!=null) return mapping;
        }
        return null;
    }

    public Object toObject(FlatProperty descriptor, String value) {
        for (Iterator iterator = list.iterator(); iterator.hasNext();) {
            StringMapper stringMapper = (StringMapper) iterator.next();
            Object mapping=stringMapper.toObject(descriptor, value);
            if (mapping!=null) return mapping;
        }
        return null;
    }

    public static DelegatingStringMapper createWithDefaultMapper(){
        DelegatingStringMapper mapper = new DelegatingStringMapper();
        mapper.add(new DefaultStringMapper());
        return mapper;
    }
}
